/**
 * @file 浏览记录 IPC 处理器
 * @description 处理渲染进程与主进程之间的浏览记录数据库操作通信
 * @author 黄敏
 * @version 1.0.0
 * @since 2025-08-05
 */

import type {
  BrowsingHistory,
  DatabaseResult,
  QueryBrowsingHistoryParams as SharedQueryParams,
  UpdateBrowsingHistoryInput as SharedUpdateInput
} from '~shared/types/browsing-history'
import type { BrowsingHistoryModel } from '#/database'
import { ipcMain } from 'electron'
import { BrowsingHistoryService } from '#/database'
import { BROWSING_HISTORY_CHANNELS } from '~shared/ipc-topic'

/** 将 Realm 模型转换为可通过 IPC 传输的纯对象 */
function toDTO(m: BrowsingHistoryModel): BrowsingHistory {
  return {
    id: m.id ?? 0,
    url: m.url,
    title: m.title ?? undefined,
    favicon_url: m.favicon_url ?? undefined,
    visit_time: m.visit_time.getTime(),
    visit_count: m.visit_count,
    created_at: m.created_at.getTime(),
    updated_at: m.updated_at.getTime()
  }
}

/** 适配渲染层的查询参数为服务层使用的参数 */
function adaptQueryParams(params: SharedQueryParams | undefined) {
  const p = params || {}
  return {
    url: p.url_pattern,
    title: p.title_pattern,
    startTime: p.start_time ? new Date(p.start_time) : undefined,
    endTime: p.end_time ? new Date(p.end_time) : undefined,
    limit: p.limit,
    offset: p.offset,
    sortBy: (p.order_by as any) || 'visit_time',
    sortOrder: (p.order_direction?.toLowerCase() === 'asc' ? 'asc' : 'desc') as 'asc' | 'desc'
  }
}

/**
 * 注册浏览记录相关的 IPC 处理器
 */
export function registerBrowsingHistoryHandlers(): void {
  const service = BrowsingHistoryService.getInstance()

  // ==================== 删除操作 ====================

  /**
   * 删除浏览记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.DELETE_RECORD,
    async (_, id: number): Promise<DatabaseResult<void>> => {
      try {
        console.log(`🗑️ 收到删除浏览记录请求: ID ${id}`)
        return await service.deleteRecordByLegacyId(id)
      } catch (error) {
        console.error('❌ IPC 删除浏览记录失败:', error)
        return {
          success: false,
          error: `IPC 删除浏览记录失败: ${error}`
        }
      }
    }
  )

  /**
   * 批量删除浏览记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.DELETE_RECORDS,
    async (_, ids: number[]): Promise<DatabaseResult<void>> => {
      try {
        console.log(`🗑️ 收到批量删除浏览记录请求: ${ids.length} 条记录`)
        return await service.deleteRecordsByLegacyIds(ids)
      } catch (error) {
        console.error('❌ IPC 批量删除浏览记录失败:', error)
        return {
          success: false,
          error: `IPC 批量删除浏览记录失败: ${error}`
        }
      }
    }
  )

  /**
   * 清空所有浏览记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.CLEAR_ALL_RECORDS,
    async (): Promise<DatabaseResult<void>> => {
      try {
        console.log('🧹 收到清空所有浏览记录请求')
        return await service.clearAllRecords()
      } catch (error) {
        console.error('❌ IPC 清空所有浏览记录失败:', error)
        return {
          success: false,
          error: `IPC 清空所有浏览记录失败: ${error}`
        }
      }
    }
  )

  // ==================== 查询操作 ====================

  /**
   * 根据ID查找浏览记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.FIND_BY_ID,
    async (_, id: number): Promise<DatabaseResult<BrowsingHistory | null>> => {
      try {
        console.log(`🔍 收到根据ID查找浏览记录请求: ID ${id}`)
        const res = await service.findByLegacyId(id)
        return res.success
          ? { success: true, data: res.data ? toDTO(res.data) : null }
          : { success: false, error: res.error }
      } catch (error) {
        console.error('❌ IPC 根据ID查找浏览记录失败:', error)
        return {
          success: false,
          error: `IPC 根据ID查找浏览记录失败: ${error}`
        }
      }
    }
  )

  /**
   * 根据URL查找浏览记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.FIND_BY_URL,
    async (_, url: string): Promise<DatabaseResult<BrowsingHistory | null>> => {
      try {
        console.log(`🔍 收到根据URL查找浏览记录请求: ${url}`)
        const res = await service.findByUrl(url)
        return res.success
          ? { success: true, data: res.data ? toDTO(res.data) : null }
          : { success: false, error: res.error }
      } catch (error) {
        console.error('❌ IPC 根据URL查找浏览记录失败:', error)
        return {
          success: false,
          error: `IPC 根据URL查找浏览记录失败: ${error}`
        }
      }
    }
  )

  /**
   * 查询浏览记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.QUERY_RECORDS,
    async (_, params: SharedQueryParams): Promise<DatabaseResult<BrowsingHistory[]>> => {
      try {
        console.log('🔍 收到查询浏览记录请求')
        const res = await service.queryRecords(adaptQueryParams(params))
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO) }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 查询浏览记录失败:', error)
        return {
          success: false,
          error: `IPC 查询浏览记录失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 搜索浏览记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.SEARCH_RECORDS,
    async (_, keyword: string, limit?: number): Promise<DatabaseResult<BrowsingHistory[]>> => {
      try {
        const res = await service.searchRecords(keyword, limit)
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO) }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 搜索浏览记录失败1:', error)
        return {
          success: false,
          error: `IPC 搜索浏览记录失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 获取最近访问的记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.GET_RECENT_RECORDS,
    async (_, limit?: number): Promise<DatabaseResult<BrowsingHistory[]>> => {
      try {
        console.log(`🔍 收到获取最近访问记录请求: 限制 ${limit || 20} 条`)
        const res = await service.getRecentRecords(limit)
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO) }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 获取最近访问记录失败:', error)
        return {
          success: false,
          error: `IPC 获取最近访问记录失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 获取访问次数最多的记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.GET_MOST_VISITED_RECORDS,
    async (_, limit?: number): Promise<DatabaseResult<BrowsingHistory[]>> => {
      try {
        console.log(`🔍 收到获取最常访问记录请求: 限制 ${limit || 20} 条`)
        const res = await service.getMostVisitedRecords(limit)
        return res.success
          ? { success: true, data: (res.data || []).map(toDTO) }
          : { success: false, error: res.error, data: [] }
      } catch (error) {
        console.error('❌ IPC 获取最常访问记录失败:', error)
        return {
          success: false,
          error: `IPC 获取最常访问记录失败: ${error}`,
          data: []
        }
      }
    }
  )

  /**
   * 获取记录总数
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.GET_RECORD_COUNT,
    async (): Promise<DatabaseResult<number>> => {
      try {
        console.log('📊 收到获取记录总数请求')
        return await service.getRecordCount()
      } catch (error) {
        console.error('❌ IPC 获取记录总数失败:', error)
        return {
          success: false,
          error: `IPC 获取记录总数失败: ${error}`,
          data: 0
        }
      }
    }
  )

  // ==================== 修改操作 ====================

  /**
   * 更新浏览记录
   */
  ipcMain.handle(
    BROWSING_HISTORY_CHANNELS.UPDATE_RECORD,
    async (_, input: SharedUpdateInput): Promise<DatabaseResult<BrowsingHistory>> => {
      try {
        console.log(`📝 收到更新浏览记录请求: ID ${input.id}`)
        const { id, visit_time, ...rest } = input
        const res = await service.updateRecordByLegacyId(id, {
          ...rest,
          visit_time: typeof visit_time === 'number' ? new Date(visit_time) : undefined
        })
        return res.success && res.data
          ? { success: true, data: toDTO(res.data) }
          : { success: false, error: res.error || '记录不存在' }
      } catch (error) {
        console.error('❌ IPC 更新浏览记录失败:', error)
        return {
          success: false,
          error: `IPC 更新浏览记录失败: ${error}`
        }
      }
    }
  )

  console.log('✅ 浏览记录 IPC 处理器已注册')
}
